package com.ophiux.utils.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * AES常用解密加密工具类
 * 下面解决32秘钥方法
 * https://pan.baidu.com/s/1EExbUE1cLNHxgOeM4_JJ-A    提取密码：f5ed
 * %JDK_Home%\jre\lib\security目录下,对应覆盖local_policy.jar和US_export_policy.jar两个文件
 * %JRE_Home%\lib\security目录下，也需要对应覆盖这两个文件。
 */
public class AesUtil {

    /**
     * 默认的字符编码
     */
    private static final String DEFAULT_CHARSET = "utf-8";

    /**
     * 算法
     */
    private static String ALGORITHM = "AES";


    /**
     * 算法/模式/填充
     **/
    private static final String CipherMode = "AES/ECB/PKCS5Padding";


    /**
     * 记录日志
     **/
    private final static Logger logger = LoggerFactory.getLogger(AesUtil.class);

    private AesUtil() {
    }

    /**
     * 解密AES 32位
     *
     * @param sSrc      解密的内容
     * @param secretKey 秘钥
     * @return 解密后的明文 数据
     */
    public static String decrypt(String sSrc, String secretKey) {

        if (secretKey == null) {
            logger.error("需要加密的秘钥为空");
            return null;
        }
        try {
            byte[] raw = secretKey.getBytes(DEFAULT_CHARSET);
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            // 先用base64解密
            byte[] encryptedArr = Base64.getDecoder().decode(sSrc);
            byte[] original = cipher.doFinal(encryptedArr);
            return new String(original, DEFAULT_CHARSET);
        } catch (Exception ex) {
            logger.error("AES解密失败", ex);
            return null;
        }
    }


    /**
     * 加密32位
     *
     * @param sSrc 需要加密的内容
     * @param sKey 秘钥
     * @return 加密的内容
     */
    public static String encrypt(String sSrc, String sKey) {
    	java.security.Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        if (sKey == null) {
            logger.error("需要加密的秘钥为空");
            return null;
        }
        try {
            byte[] raw = sKey.getBytes(DEFAULT_CHARSET);
            SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            byte[] encrypted = cipher.doFinal(sSrc.getBytes(DEFAULT_CHARSET));

            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception ex) {
            logger.error("AES加密失败", ex);
            return null;
        }
    }
    
    public static void main(String[] args) {
    	String dd = encrypt("1", "e006338d2d48c23b72926d645a676b26");
    	System.out.println(dd);
	}

}
